import type {
  ActionType,
  PageInfo,
  ParamsType,
  ProColumns,
  RequestData,
} from '@ant-design/pro-components';
import { EditableProTable, FooterToolbar } from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, message } from 'antd';
import React, { useCallback, useRef, useState } from 'react';

interface EditTableProps<T, U> {
  removeRule?: (keys: T[]) => Promise<void>;
  columns: ProColumns<T>[];
  onRowClick?: (entity: T) => void;
  renderToolBar?: () => React.ReactNode[];
  request: (params: U, sorter: any, filter: any) => Promise<RequestData<T>>;
  onOK?: (params: T) => Promise<void>;
}

const EditTable = <T extends Record<string, any>, U extends ParamsType>({
  removeRule,
  columns,
  renderToolBar,
  request,
  onOK,
}: EditTableProps<T, U>) => {
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<T[]>([]);
  const intl = useIntl();
  const [messageApi, contextHolder] = message.useMessage();
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [pageInfo, setPageInfo] = useState<PageInfo>({ current: 1, pageSize: 20, total: 1 });

  const handleRemove = useCallback(async () => {
    if (!selectedRowsState?.length) {
      messageApi.warning('请选择删除项');
      return;
    }
    await removeRule?.(selectedRowsState);
    setSelectedRows([]);
    actionRef.current?.reloadAndRest?.();
    messageApi.success('删除成功，即将刷新！');
  }, [removeRule, selectedRowsState]);

  const onFinish = async (value: T) => {
    onOK?.(value);
  };

  return (
    <>
      {contextHolder}
      <EditableProTable<T>
        rowKey="code"
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.title',
          defaultMessage: 'Enquiry form',
        })}
        pagination={{
          pageSize: pageInfo.pageSize,
          current: pageInfo.current,
          total: pageInfo.total,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
          onChange: (page, pageSize) => {
            setPageInfo({ current: page, pageSize, total: pageInfo.total });
          },
        }}
        actionRef={actionRef}
        maxLength={0}
        scroll={{ x: 960 }}
        toolBarRender={renderToolBar}
        search={{ labelWidth: 120 }}
        loading={false}
        columns={columns}
        request={async (params, sorter, filter) => {
          const response = await request(params as U, sorter, filter);
          return {
            data: response.data,
            total: response.total,
            success: response.success,
          };
        }}
        editable={{
          type: 'multiple',
          editableKeys,
          onSave: async (rowKey, data) => await onFinish(data),
          onChange: setEditableRowKeys,
          actionRender: (row, config, defaultDom) => [defaultDom.save, defaultDom.cancel],
        }}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="Chosen" />{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
            </div>
          }
        >
          <Button onClick={handleRemove}>
            <FormattedMessage
              id="pages.searchTable.batchDeletion"
              defaultMessage="Batch deletion"
            />
          </Button>
        </FooterToolbar>
      )}
    </>
  );
};

export default EditTable;
